#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -z "$LMD_DATA_ROOT" ]; then
    echo "Error: Env LMD_DATA_ROOT is not defined."
    exit 1
else
    echo "Env LMD_DATA_ROOT: $LMD_DATA_ROOT"
fi

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/env_node"

export GLOBAL_TOOLS_DIR="${LMD_DATA_ROOT}/scripts/global-tools"

NODE_JS_DIR="${LMD_DATA_ROOT}/scripts/global-tools/node"

mkdir -p "$NODE_JS_DIR"
if [ -d "$NODE_JS_DIR" ]; then
    echo "Node Dir: "$NODE_JS_DIR
else
    echo "Error, Node Dir dose not exist, please retry. "$NODE_JS_DIR
    exit 1
fi

cd "$NODE_JS_DIR"

pwd

source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/n8n/env"

function install_node {
    NODE_DOWNLOAD_PREFIX=https://registry.npmmirror.com/-/binary/node/v${_NODE_VERSION}
    
    if [ -f /etc/os-release ]; then
        echo "Linux system."
        echo "Not yet support."
    elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
        echo "macOS system."
        ARCH=$(uname -m)
        
        if [ "$ARCH" == "x86_64" ]; then
            echo "Intel-based Mac."
            DOWNLOAD_FILE_NAME=node-v${_NODE_VERSION}-darwin-x64.tar.xz
            NODE_VER_DIR=node-v${_NODE_VERSION}-darwin-x64
        elif [ "$ARCH" == "arm64" ]; then
            echo "Apple Silicon (M-series) Mac."
            DOWNLOAD_FILE_NAME=node-v${_NODE_VERSION}-darwin-arm64.tar.xz
            NODE_VER_DIR=node-v${_NODE_VERSION}-darwin-arm64
        fi
        
        download_file
        tar -xf $DOWNLOAD_FILE_NAME
        NODE_BINARY_DIR="$NODE_JS_DIR/$NODE_VER_DIR/bin"
    elif current_os_is_windows; then
        echo "Windows system. get 7z"
        source "$LMD_BASE_INSTALL_SCRIPT_DIR/global/install_7z.sh"

        cd $NODE_JS_DIR
        DOWNLOAD_FILE_NAME=node-v${_NODE_VERSION}-win-x64.7z
        NODE_VER_DIR=node-v${_NODE_VERSION}-win-x64
        
        download_file
        7zr x "${DOWNLOAD_FILE_NAME}" -o"./" -y
        NODE_BINARY_DIR="$NODE_JS_DIR/$NODE_VER_DIR"
    else
        echo "Unknown OS"
    fi
}

function download_file {
    NODE_DOWNLOAD_URL=${NODE_DOWNLOAD_PREFIX}/${DOWNLOAD_FILE_NAME}
    echo "start download ${NODE_DOWNLOAD_URL}"
    
    curl --ssl-no-revoke -L -C - --retry 7 -o "$DOWNLOAD_FILE_NAME" $NODE_DOWNLOAD_URL
    # curl: (56) HTTP server doesn't seem to support byte ranges. Cannot resume.
    exit_code=$?
    if [ $exit_code -eq 56 ]; then
        rm -f ./$DOWNLOAD_FILE_NAME
        echo "retry download without byte ranges"
        curl --ssl-no-revoke -L --retry 7 -o $DOWNLOAD_FILE_NAME $NODE_DOWNLOAD_URL
    fi

    echo "download ok."
}

install_node

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias_node.sh"
